package com.xpalive.config.swagger;

import io.swagger.annotations.Api;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.ApiSelectorBuilder;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.List;

/**
 * Springboot启动后频繁打印错误日志 /null/swagger-ui.html解决方案
 * 经过一番查找发现是端口被占用。
 * netstat -ano|findstr "8061"
 * tasklist | findstr "8444"
 * https://blog.csdn.net/qq_16410733/article/details/99542038
 */

@Configuration
@EnableSwagger2
public class SwaggerConfiguration {

    @Bean
    public Docket api() {
        Docket docket = new Docket(DocumentationType.SWAGGER_2);
        ApiInfo apiInfo = new ApiInfoBuilder().title("JAVA API").version("V1.0.0").build();
        docket.apiInfo(apiInfo).globalOperationParameters(defaultParameters());
        ApiSelectorBuilder apis = docket.select();
        apis.apis(RequestHandlerSelectors.withClassAnnotation(Api.class));
        return apis.build();
    }


    private List<Parameter> defaultParameters() {
        ParameterBuilder zwToken = new ParameterBuilder();
        zwToken.parameterType("header")
                .name("zw-token") // 参数名
                .defaultValue("super")
                .description("API调用时传入,登录除外")
                .modelRef(new ModelRef("string"))
                .required(true).build();

        ParameterBuilder acceptLanguage = new ParameterBuilder();
        acceptLanguage.parameterType("header")
                .name("accept-language")
                .defaultValue("zh-CN")
                .description("API调用时传入,登录除外")
                .modelRef(new ModelRef("string"))
                .required(true).build();

        List<Parameter> parameters = new ArrayList<>();
        parameters.add(zwToken.build());
        parameters.add(acceptLanguage.build());

        return parameters;
    }
}
